package cn.itcast.wushangxiantu.Activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.itcast.wushangxiantu.BaseAdapter.ChongWuBagGriveViewAdapter;
import cn.itcast.wushangxiantu.BaseAdapter.ChongWuTuJianAdatper;
import cn.itcast.wushangxiantu.UserData.User;
import cn.itcast.wushangxiantu.UserData.UserChongWu;
import cn.itcast.wushangxiantu.OkhttpUtil;
import cn.itcast.wushangxiantu.R;
import cn.itcast.wushangxiantu.ToastUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class Chongwu extends AppCompatActivity implements View.OnClickListener {

    private TextView tvNumber;
    private GridView gvBag;
    private ChongWuBagGriveViewAdapter adapter;
    private UserChongWu userChongWu;
    private TextView tvName;
    private TextView tvDj;
    private TextView tvShuoMing;
    private TextView tvHeCheng;
    private TextView tvFenJie;
    private int cwid = 0;//背包编号
    private TextView tvShengJi;
    private TextView tvTuPo;
    private TextView tvJiNeng;
    private TextView tvChuZhan;
    private int cw_id = 0;
    private int cw_i = 0;//技能栏对应的id
    private ListView tvLv;
    private TextView tvTuJian;
    private ChongWuTuJianAdatper tuJianAdatper;
    private ImageView iv;
    private Integer imgs[] = {R.drawable.chongwu1, R.drawable.chongwu2, R.drawable.chongwu3, R.drawable.chongwu4, R.drawable.chongwu5, R.drawable.chongwu6,
            R.drawable.chongwu7, R.drawable.chongwu8, R.drawable.chongwu9, R.drawable.chongwu10, R.drawable.chongwu11,
            R.drawable.chongwu12, R.drawable.chongwu13, R.drawable.chongwu14, R.drawable.chongwu15};
    private TextView tvYiJian;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chongwu);
        initView();
        zhunbei();
    }

    private void zhunbei() {
        getbag(Login.getUser().getUsernumber());
    }

    private void getbag(String usernumber) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=getChongWuYuLan", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("chongwu1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("chongwu2", src);
                UserChongWu chongWu = null;
                try {
                    chongWu = new Gson().fromJson(src, UserChongWu.class);
                } catch (Exception e) {
                    chongWu = null;
                }
                Message message = new Message();
                message.obj = chongWu;
                message.what = 1;
                handler.sendMessage(message);
            }
        });
    }

    private void hecheng(String usernumber) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=ChongWuHeCheng", new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("hecheng1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("hecheng2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 2;
                handler.sendMessage(message);
            }
        });
    }

    private void fenjie(String usernumber, int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=ChongWuFenJie" + "&id=" + id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("fenjie1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("fenjie2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private void ShengJi(String usernumber, int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=ChongWuShengJi" + "&id=" + id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("shengji1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("shengji2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 4;
                handler.sendMessage(message);
            }
        });
    }

    private void ChuZhan(String usernumber, int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=chuzhan" + "&id=" + id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("shengji1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("shengji2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 8;
                handler.sendMessage(message);
            }
        });
    }

    private void TuPo(String usernumber, int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=ChongWuTuPo" + "&id=" + id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("tupo1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("tupo2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {
                    user = null;
                }
                Message message = new Message();
                message.obj = user;
                message.what = 5;
                handler.sendMessage(message);
            }
        });
    }

    private void ChongWuShangJia(int id, int price) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + Login.getUser().getUsernumber() + "&need=chongwushangjia" +
                "&id=" + id + "&price=" + price, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("shangjia2", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("shangjia4", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 6;
                handler.sendMessage(message);
            }
        });
    }

    private void ShiYongJiNeng(String usernumer, int id) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumer + "&need=chongwujineng" +
                "&id=" + id, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("jineng1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("jineng2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 7;
                handler.sendMessage(message);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            switch (message.what) {
                case 1:
                    userChongWu = (UserChongWu) message.obj;
                    if (null != userChongWu) {
                        if (null == userChongWu.getStw()) {
                            if (adapter == null) {
                                adapter = new ChongWuBagGriveViewAdapter(getApplicationContext());
                            }
                            adapter.setChongWu(userChongWu);
                            gvBag.setAdapter(adapter);
                            tvNumber.setText("当前技能残页:" + userChongWu.getNumber());
                        } else {
                            ToastUtil.toast(getApplicationContext(), userChongWu.getStw());
                        }
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 2:
                    User user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("合成详情", user.getStw());
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 3:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("分解详情", user.getStw());
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 4:
                case 9:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("升级详情", user.getStw());
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 5:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("进阶详情", user.getStw());
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 6:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("上架详情", user.getStw());
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 7:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("技能使用详情", user.getStw());
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
                case 8:
                    user = (User) message.obj;
                    if (null != user) {
                        GeneralDialog("技能详情", user.getStw());
                        Login.getUser().setCw_id(cwid);
                        Login.getUser().setCwid(cw_id);
                        tvDj.setText("");
                        tvName.setText("");
                        tvShuoMing.setText("");
                        iv.setImageResource(0);
                        cwid = 0;
                        getbag(Login.getUser().getUsernumber());
                    } else {
                        ToastUtil.toast(getApplicationContext(), "服务器炸了");
                    }
                    break;
            }
            return false;
        }
    });

    private void initView() {
        tvNumber = (TextView) findViewById(R.id.tvNumber);
        gvBag = (GridView) findViewById(R.id.gvBag);
        tvName = (TextView) findViewById(R.id.tvName);
        tvDj = (TextView) findViewById(R.id.tvDj);
        tvShuoMing = (TextView) findViewById(R.id.tvShuoMing);
        gvBag.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                iv.setImageResource(imgs[userChongWu.getChongwu().get(i).getCw_id() - 1]);
                cw_i = i;
                cw_id = userChongWu.getChongwu().get(i).getCw_id();
                if (null != userChongWu) {
                    tvDj.setText(userChongWu.getChongwu().get(i).getXj() + "阶" + userChongWu.getChongwu().get(i).getDj() + "级");
                    tvName.setText(userChongWu.getChongwu().get(i).getName());
                    String jineng = "技能:" + userChongWu.getChongwu().get(i).getShuoming();

                    Date currentTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String newTime = formatter.format(currentTime); // 当前本地时间
                    long OTime = 0;
                    long NTime = 0;
                    try {
                        OTime = formatter.parse(userChongWu.getChongwu().get(i).getCd()).getTime();
                        NTime = formatter.parse(newTime).getTime();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    long diff = (NTime - OTime);
                    Log.v("13213", diff + "");
                    switch (userChongWu.getChongwu().get(i).getCw_id()) {
                        case 1:
                        case 2:
                        case 3:
                        case 15:
                            if (diff >= 43200000) {
                                jineng += "【技能就绪】";
                            } else {
                                diff = 43200000 - diff;
                                if (diff < 60000) {
                                    jineng += "【还需：" + (diff / 1000) + "秒】";
                                } else if (diff < 3600000) {
                                    jineng += "【还需：" + (diff / 60000) + "分钟】";
                                } else {
                                    jineng += "【还需：" + (diff / 3600000) + "小时】";
                                }
                            }
                            break;
                        case 5:
                        case 6:
                            if (diff > 43200000 - userChongWu.getChongwu().get(i).getXj() * 3600000) {
                                jineng += "【技能就绪】";
                            } else {
                                diff = 43200000 - userChongWu.getChongwu().get(i).getXj() * 3600000 - diff;
                                if (diff < 60000) {
                                    jineng += "【还需：" + (diff / 1000) + "秒】";
                                } else if (diff < 3600000) {
                                    jineng += "【还需：" + (diff / 60000) + "分钟】";
                                } else {
                                    jineng += "【还需：" + (diff / 3600000) + "小时】";
                                }
                            }
                            break;
                    }
                    tvShuoMing.setText(jineng);
                    cwid = userChongWu.getChongwu().get(i).getId();
                    cw_id = userChongWu.getChongwu().get(i).getCw_id();
                }
            }
        });
        tvHeCheng = (TextView) findViewById(R.id.tvHeCheng);
        tvHeCheng.setOnClickListener(this);
        tvFenJie = (TextView) findViewById(R.id.tvFenJie);
        tvFenJie.setOnClickListener(this);
        tvShengJi = (TextView) findViewById(R.id.tvShengJi);
        tvShengJi.setOnClickListener(this);
        tvShengJi.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                //一键升级
                GeneralDialog("技能升级", "确定一键升级到满级？", 4);
                return false;
            }
        });
        tvTuPo = (TextView) findViewById(R.id.tvTuPo);
        tvTuPo.setOnClickListener(this);
        tvJiNeng = (TextView) findViewById(R.id.tvJiNeng);
        tvJiNeng.setOnClickListener(this);
        tvChuZhan = (TextView) findViewById(R.id.tvChuZhan);
        tvChuZhan.setOnClickListener(this);
        tvLv = (ListView) findViewById(R.id.tvLv);
        tvTuJian = (TextView) findViewById(R.id.tvTuJian);
        tvTuJian.setOnClickListener(this);
        tvLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                GeneralDialog(tuJianAdatper.chongwuName.get(i), tuJianAdatper.chongwuShuoMing.get(i));
            }
        });
        iv = (ImageView) findViewById(R.id.iv);
        tvYiJian = (TextView) findViewById(R.id.tvYiJian);
        tvYiJian.setOnClickListener(this);
    }

    /**
     * 技能上架
     *
     * @param context
     * @param id      技能背包id
     */
    private void GeneralDialogDingJia(final Context context, final int id) {
        /**
         * 编辑框
         * 1标题
         */
        AlertDialog dialog;
        final EditText editText = new EditText(context);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        InputFilter[] filters = {new InputFilter.LengthFilter(9)};
        editText.setFilters(filters);
        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle("输入价格5-999999999")
                .setView(editText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (editText.getText().toString().trim().equals("") || editText.getText().length() >= 16) {
                            dialogInterface.dismiss();
                            ToastUtil.toast(context, "输入有误");
                            return;
                        }
                        int chushouNum = Integer.parseInt(editText.getText().toString().trim());
                        if (chushouNum < 5) {
                            ToastUtil.toast(context, "价格有误");
                        } else {
                            ChongWuShangJia(id, chushouNum);
                        }
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    public void GeneralDialog(String head, String content) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(head)

                .setMessage(content)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    public void GeneralDialog(String head, String content, final int num) {
        /**
         * 普通对话框
         * 1标题
         * 2内容
         */
        AlertDialog dialog;
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(head)

                .setMessage(content)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (num) {
                            case 0:
                                hecheng(Login.getUser().getUsernumber());
                                break;
                            case 1:
                                fenjie(Login.getUser().getUsernumber(), cwid);
                                break;
                            case 2:
                                ShengJi(Login.getUser().getUsernumber(), cwid);
                                break;
                            case 3:
                                TuPo(Login.getUser().getUsernumber(), cwid);
                                break;
                            case 4:
                                ShengJiMax(Login.getUser().getUsernumber(), Login.getUser().getPassword(), cwid);
                                break;
                        }
                        dialogInterface.dismiss();
                    }
                });
        dialog = builder.create();
        dialog.show();
    }

    private void ShengJiMax(String usernumber, String password, int cwid) {
        OkhttpUtil.getRequest(OkhttpUtil.URL_LOG + "userNumber=" + usernumber + "&need=ChongWuShengJiMax" +
                "&id=" + cwid + "&passWord=" + password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.v("shengji1", e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String src = response.body().string();
                Log.v("shengji2", src);
                User user = null;
                try {
                    user = new Gson().fromJson(src, User.class);
                } catch (Exception e) {

                }
                Message message = new Message();
                message.obj = user;
                message.what = 9;
                handler.sendMessage(message);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvHeCheng:
                GeneralDialog("合成技能书", "确定花费30技能残页合成一个全新的技能书吗？", 0);
                break;
            case R.id.tvFenJie:
                if (cwid != 0) {
                    GeneralDialog("分解技能", "分解技能术可获得技能残页*" + (userChongWu.getChongwu().get(cw_i).getXj() * 10), 1);
                } else {
                    ToastUtil.toast(getApplicationContext(), "还未选择技能书");
                }
                break;
            case R.id.tvShengJi:
                if (cwid != 0) {
                    GeneralDialog("升级技能", "即将花费金币" + (userChongWu.getChongwu().get(cw_i).getDj() * 200), 2);
                } else {
                    ToastUtil.toast(getApplicationContext(), "还未选择技能");
                }
                break;
            case R.id.tvTuPo:
                if (cwid != 0) {
                    GeneralDialog("技能进阶", "即将花费石魂*" + userChongWu.getChongwu().get(cw_i).getXj() + "\n无论成功失败等级都降至1级", 3);
                } else {
                    ToastUtil.toast(getApplicationContext(), "还未选择技能");
                }
                break;
            case R.id.tvJiNeng:
                if (cwid != 0) {
                    ShiYongJiNeng(Login.getUser().getUsernumber(), cwid);
                } else {
                    ToastUtil.toast(getApplicationContext(), "还未选择技能");
                }
                break;
            case R.id.tvChuZhan:
                if (cwid != 0) {
                    ChuZhan(Login.getUser().getUsernumber(), cwid);
                } else {
                    ToastUtil.toast(getApplicationContext(), "还未选择技能");
                }
                break;
            case R.id.tvTuJian:
                tvDj.setText("");
                tvName.setText("");
                tvShuoMing.setText("");
                iv.setImageResource(0);
                cwid = 0;
                if (tvTuJian.getText().toString().trim().equals("图鉴")) {
                    gvBag.setVisibility(View.GONE);
                    tvLv.setVisibility(View.VISIBLE);
                    if (tuJianAdatper == null) {
                        tuJianAdatper = new ChongWuTuJianAdatper(Chongwu.this);
                        tvLv.setAdapter(tuJianAdatper);
                    }
                    tvTuJian.setText("返回技能栏");
                } else {
                    gvBag.setVisibility(View.VISIBLE);
                    tvLv.setVisibility(View.GONE);
                    tvTuJian.setText("图鉴");
                }
                break;
            case R.id.tvYiJian:
                GeneralDialog("技能升级", "确定一键升级到满级？", 4);
                break;
        }
    }
}